package com.ytf.auth.authentication.service;

import com.ytf.core.web.application.UserAppService;
import com.ytf.core.web.pojo.vo.RoleVo;
import com.ytf.core.web.pojo.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @className: MysqlUserDetailsManager
 * @author: YTF
 * @date: 2025/4/30 9:18
 * @description:
 */
@Service
public class CustomUserDetailsManager extends InMemoryUserDetailsManager {

    @Autowired
    private UserAppService userAppService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        UserVo userVo = userAppService.getByUsername(username);

        List<RoleVo> roleVos = userVo.getRoleVos();
        // 将 List 转换为 String 数组
        String[] array = roleVos.stream().map(RoleVo::getRoleKey).toArray(String[]::new);
        // 构建 UserDetails 对象
        return User.builder()
                .username(userVo.getUsername())
                .password(userVo.getPassword())
                .roles(array)
                .build();
    }

}

